package com.yonglian.management.web.rest;

import static com.yonglian.management.domain.ActivityPlanAsserts.*;
import static com.yonglian.management.web.rest.TestUtil.createUpdateProxyForBean;
import static com.yonglian.management.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonglian.management.IntegrationTest;
import com.yonglian.management.domain.ActivityPlan;
import com.yonglian.management.repository.ActivityPlanRepository;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link ActivityPlanResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ActivityPlanResourceIT {

    private static final String DEFAULT_PLAN_NAME = "AAAAAAAAAA";
    private static final String UPDATED_PLAN_NAME = "BBBBBBBBBB";

    private static final ZonedDateTime DEFAULT_CREATE_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_CREATE_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final String ENTITY_API_URL = "/api/activity-plans";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private ObjectMapper om;

    @Autowired
    private ActivityPlanRepository activityPlanRepository;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restActivityPlanMockMvc;

    private ActivityPlan activityPlan;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ActivityPlan createEntity(EntityManager em) {
        ActivityPlan activityPlan = new ActivityPlan().planName(DEFAULT_PLAN_NAME).createTime(DEFAULT_CREATE_TIME);
        return activityPlan;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ActivityPlan createUpdatedEntity(EntityManager em) {
        ActivityPlan activityPlan = new ActivityPlan().planName(UPDATED_PLAN_NAME).createTime(UPDATED_CREATE_TIME);
        return activityPlan;
    }

    @BeforeEach
    public void initTest() {
        activityPlan = createEntity(em);
    }

    @Test
    @Transactional
    void createActivityPlan() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the ActivityPlan
        var returnedActivityPlan = om.readValue(
            restActivityPlanMockMvc
                .perform(
                    post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityPlan))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            ActivityPlan.class
        );

        // Validate the ActivityPlan in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        assertActivityPlanUpdatableFieldsEquals(returnedActivityPlan, getPersistedActivityPlan(returnedActivityPlan));
    }

    @Test
    @Transactional
    void createActivityPlanWithExistingId() throws Exception {
        // Create the ActivityPlan with an existing ID
        activityPlan.setId(1L);

        long databaseSizeBeforeCreate = getRepositoryCount();

        // An entity with an existing ID cannot be created, so this API call must fail
        restActivityPlanMockMvc
            .perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityPlan)))
            .andExpect(status().isBadRequest());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void checkPlanNameIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        activityPlan.setPlanName(null);

        // Create the ActivityPlan, which fails.

        restActivityPlanMockMvc
            .perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityPlan)))
            .andExpect(status().isBadRequest());

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllActivityPlans() throws Exception {
        // Initialize the database
        activityPlanRepository.saveAndFlush(activityPlan);

        // Get all the activityPlanList
        restActivityPlanMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(activityPlan.getId().intValue())))
            .andExpect(jsonPath("$.[*].planName").value(hasItem(DEFAULT_PLAN_NAME)))
            .andExpect(jsonPath("$.[*].createTime").value(hasItem(sameInstant(DEFAULT_CREATE_TIME))));
    }

    @Test
    @Transactional
    void getActivityPlan() throws Exception {
        // Initialize the database
        activityPlanRepository.saveAndFlush(activityPlan);

        // Get the activityPlan
        restActivityPlanMockMvc
            .perform(get(ENTITY_API_URL_ID, activityPlan.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(activityPlan.getId().intValue()))
            .andExpect(jsonPath("$.planName").value(DEFAULT_PLAN_NAME))
            .andExpect(jsonPath("$.createTime").value(sameInstant(DEFAULT_CREATE_TIME)));
    }

    @Test
    @Transactional
    void getNonExistingActivityPlan() throws Exception {
        // Get the activityPlan
        restActivityPlanMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putExistingActivityPlan() throws Exception {
        // Initialize the database
        activityPlanRepository.saveAndFlush(activityPlan);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityPlan
        ActivityPlan updatedActivityPlan = activityPlanRepository.findById(activityPlan.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedActivityPlan are not directly saved in db
        em.detach(updatedActivityPlan);
        updatedActivityPlan.planName(UPDATED_PLAN_NAME).createTime(UPDATED_CREATE_TIME);

        restActivityPlanMockMvc
            .perform(
                put(ENTITY_API_URL_ID, updatedActivityPlan.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(updatedActivityPlan))
            )
            .andExpect(status().isOk());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedActivityPlanToMatchAllProperties(updatedActivityPlan);
    }

    @Test
    @Transactional
    void putNonExistingActivityPlan() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityPlan.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restActivityPlanMockMvc
            .perform(
                put(ENTITY_API_URL_ID, activityPlan.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(activityPlan))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchActivityPlan() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityPlan.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPlanMockMvc
            .perform(
                put(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(activityPlan))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamActivityPlan() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityPlan.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPlanMockMvc
            .perform(put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityPlan)))
            .andExpect(status().isMethodNotAllowed());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateActivityPlanWithPatch() throws Exception {
        // Initialize the database
        activityPlanRepository.saveAndFlush(activityPlan);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityPlan using partial update
        ActivityPlan partialUpdatedActivityPlan = new ActivityPlan();
        partialUpdatedActivityPlan.setId(activityPlan.getId());

        partialUpdatedActivityPlan.createTime(UPDATED_CREATE_TIME);

        restActivityPlanMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedActivityPlan.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedActivityPlan))
            )
            .andExpect(status().isOk());

        // Validate the ActivityPlan in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertActivityPlanUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedActivityPlan, activityPlan),
            getPersistedActivityPlan(activityPlan)
        );
    }

    @Test
    @Transactional
    void fullUpdateActivityPlanWithPatch() throws Exception {
        // Initialize the database
        activityPlanRepository.saveAndFlush(activityPlan);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityPlan using partial update
        ActivityPlan partialUpdatedActivityPlan = new ActivityPlan();
        partialUpdatedActivityPlan.setId(activityPlan.getId());

        partialUpdatedActivityPlan.planName(UPDATED_PLAN_NAME).createTime(UPDATED_CREATE_TIME);

        restActivityPlanMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedActivityPlan.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedActivityPlan))
            )
            .andExpect(status().isOk());

        // Validate the ActivityPlan in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertActivityPlanUpdatableFieldsEquals(partialUpdatedActivityPlan, getPersistedActivityPlan(partialUpdatedActivityPlan));
    }

    @Test
    @Transactional
    void patchNonExistingActivityPlan() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityPlan.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restActivityPlanMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, activityPlan.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityPlan))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchActivityPlan() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityPlan.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPlanMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityPlan))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamActivityPlan() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityPlan.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPlanMockMvc
            .perform(
                patch(ENTITY_API_URL).with(csrf()).contentType("application/merge-patch+json").content(om.writeValueAsBytes(activityPlan))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the ActivityPlan in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteActivityPlan() throws Exception {
        // Initialize the database
        activityPlanRepository.saveAndFlush(activityPlan);

        long databaseSizeBeforeDelete = getRepositoryCount();

        // Delete the activityPlan
        restActivityPlanMockMvc
            .perform(delete(ENTITY_API_URL_ID, activityPlan.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
    }

    protected long getRepositoryCount() {
        return activityPlanRepository.count();
    }

    protected void assertIncrementedRepositoryCount(long countBefore) {
        assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
    }

    protected void assertDecrementedRepositoryCount(long countBefore) {
        assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
    }

    protected void assertSameRepositoryCount(long countBefore) {
        assertThat(countBefore).isEqualTo(getRepositoryCount());
    }

    protected ActivityPlan getPersistedActivityPlan(ActivityPlan activityPlan) {
        return activityPlanRepository.findById(activityPlan.getId()).orElseThrow();
    }

    protected void assertPersistedActivityPlanToMatchAllProperties(ActivityPlan expectedActivityPlan) {
        assertActivityPlanAllPropertiesEquals(expectedActivityPlan, getPersistedActivityPlan(expectedActivityPlan));
    }

    protected void assertPersistedActivityPlanToMatchUpdatableProperties(ActivityPlan expectedActivityPlan) {
        assertActivityPlanAllUpdatablePropertiesEquals(expectedActivityPlan, getPersistedActivityPlan(expectedActivityPlan));
    }
}
